package com.jdcjk.project.car.view;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.jdcjk.Constant;
import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseFragment;
import com.jdcjk.project.account.model.entity.Result;
import com.jdcjk.project.car.model.entity.SosNumberResult;
import com.jdcjk.project.car.presenter.CarPresenter;
import com.jdcjk.util.L;
import com.jdcjk.util.PreferencesUtils;

import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by dong on 2016/12/13.
 * 设置设置
 */
public class CarSettingFragment extends BaseFragment<CarPresenter> {
    private final String TAG = CarSettingFragment.class.getSimpleName();
    private CarPresenter carPresenter;
    //设备重启指令发送button
    private Button resetTerminal_btn;
    //报警发送方式checkBox
    private CheckBox alarmSendType_cb;
    //报警发送方式选择栏spinner
    private Spinner alarmSendType_spinner;
    //sos1号码editText
    private EditText sos1_editText;
    //sos2号码editText
    private EditText sos2_editText;
    //sos3号码editText
    private EditText sos3_editText;
    //sos设置发送button
    private Button sosSend_button;
    //定位信息上报时长editText
    private EditText locationUpdataTime_editText;
    //定位信息上报设置发送button
    private Button locationUpdataTime_button;
    //超速报警速度设定editText
    private EditText overspeedAlarmSpeed_editText;
    //超速报警速度设定button
    private Button overspeedAlarmSet_button;
    //设备id
    private int terminalId;
    //用户id
    private int userId;

    //spinner选择参数
    private String alarmSendTypeSelected;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_car_setting;
    }

    @Override
    public CarPresenter bindPresenter() {
        carPresenter = new CarPresenter(getContext());
        return carPresenter;
    }


    @Override
    public void initContentView(View viewContent) {
        //顶栏返回button设置监听
        viewContent.findViewById(R.id.back_btn).setOnClickListener(this);
        resetTerminal_btn = (Button) viewContent.findViewById(R.id.reset_terminal_btn);
        resetTerminal_btn.setOnClickListener(this);
        //报警发送方式相关布局内容
        alarmSendType_cb = (CheckBox) viewContent.findViewById(R.id.alarm_send_type_cb);
        alarmSendType_spinner = (Spinner) viewContent.findViewById(R.id.alarm_send_type_spinner);
        //SOS号码相关布局内容
        sos1_editText = (EditText) viewContent.findViewById(R.id.sos1_et);
        sos2_editText = (EditText) viewContent.findViewById(R.id.sos2_et);
        sos3_editText = (EditText) viewContent.findViewById(R.id.sos3_et);
        sosSend_button = (Button) viewContent.findViewById(R.id.sos_send_btn);
        sosSend_button.setOnClickListener(this);
        //立即定位相关布局内容
        locationUpdataTime_editText = (EditText) viewContent.findViewById(R.id.location_updata_time_et);
        locationUpdataTime_button = (Button) viewContent.findViewById(R.id.location_updata_time_btn);
        locationUpdataTime_button.setOnClickListener(this);
        //超速报警相关布局内容
        overspeedAlarmSpeed_editText = (EditText) viewContent.findViewById(R.id.overspeed_alarm_speed_et);
        overspeedAlarmSet_button = (Button) viewContent.findViewById(R.id.overspeed_alarm_set_btn);
        overspeedAlarmSet_button.setOnClickListener(this);

        setSpinnerItemClick();
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();//从activity传过来的Bundle
        //获取设备Id
        terminalId = bundle.getInt(Constant.TerminalInfo.terminalId);
        userId = PreferencesUtils.getInt(getActivity(), Constant.UserInfo.id);
        carPresenter.getTerminalFamily(UrlAddress.GET_TERMINAL_FAMILY, String.valueOf(userId), new BasePresenter.OnUIThreadListener<SosNumberResult>() {
            @Override
            public void onBefore(Request request, int id) {

            }

            @Override
            public void onAfter(int id) {

            }

            @Override
            public void onError(Call call, Exception e, int i) {
                Toast.makeText(getActivity(), R.string.get_sos_number_fail, Toast.LENGTH_SHORT).show();
                L.i(TAG, "onError:e " + e);
            }

            @Override
            public void onResponse(SosNumberResult sosNumberResult) {
                switch (sosNumberResult.getStatus()) {
                    case "OK":
                        List<SosNumberResult.SosNumberBean> sosNumberBeanList = sosNumberResult.getResult();
                        //获得sos号码
                        if (sosNumberBeanList.size() >= 3) {
                            String sosThree = sosNumberBeanList.get(2).getFamilyMob();
                            sos3_editText.setText(sosThree);
                        }
                        if (sosNumberBeanList.size() >= 2) {
                            String sosTwo = sosNumberBeanList.get(1).getFamilyMob();
                            sos2_editText.setText(sosTwo);
                        }
                        if (sosNumberBeanList.size() >= 1) {
                            String sosOne = sosNumberBeanList.get(0).getFamilyMob();
                            sos1_editText.setText(sosOne);
                            String informType = sosNumberBeanList.get(0).getInformType();
                            switch (informType) {
                                case "TERRACEANDSMS":
                                    alarmSendType_spinner.setSelection(1);
                                    break;
                                case "TERRACE":
                                    alarmSendType_spinner.setSelection(0);
                                    break;
                            }
                        }
                        break;
                    case "FAILED":
                        Toast.makeText(getActivity(), sosNumberResult.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
        super.initData();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            //SOS号码设置发送button监听
            case R.id.sos_send_btn:
                boolean isOpenAlarmSend = alarmSendType_cb.isChecked();
                String sos1 = sos1_editText.getText().toString();
                String sos2 = sos2_editText.getText().toString();
                String sos3 = sos3_editText.getText().toString();
                StringBuffer mobs = new StringBuffer();
                if (!sos1.equals("")) {
                    mobs.append(sos1);
                    if (!sos2.equals("")) {
                        mobs.append("," + sos2);
                        if (!sos3.equals("")) {
                            mobs.append("," + sos3);
                        }
                    }
                } else {
                    if (!sos2.equals("")) {
                        mobs.append(sos2);
                        if (!sos3.equals("")) {
                            mobs.append("," + sos3);
                        }
                    } else {
                        if (!sos3.equals("")) {
                            mobs.append(sos3);
                        }
                    }
                }
                //判断输入内容是否可行（首先判断是否有输入内容，在判断长度是都在3-20位）
                if (!sos1.equals("") && sos1.length() < 3 || sos1.length() > 20) {
                    Toast.makeText(getActivity(), "sos1" + getResources().getString(R.string.toast_sos_info), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!sos2.equals("") && sos2.length() < 3 || sos2.length() > 20) {
                    Toast.makeText(getActivity(), "sos2" + getResources().getString(R.string.toast_sos_info), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!sos3.equals("") && sos3.length() < 3 || sos3.length() > 20) {
                    Toast.makeText(getActivity(), "sos3" + getResources().getString(R.string.toast_sos_info), Toast.LENGTH_SHORT).show();
                    return;
                }
                carPresenter.saveTermailFamily(UrlAddress.SAVE_TERMAIL_FRMILY, String.valueOf(userId), mobs.toString(), alarmSendTypeSelected, new BasePresenter.OnUIThreadListener<Result>() {
                    @Override
                    public void onBefore(Request request, int id) {

                    }

                    @Override
                    public void onAfter(int id) {

                    }

                    @Override
                    public void onError(Call call, Exception e, int i) {
                        Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Result result) {
                        switch (result.getStatus()) {
                            case "OK":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                            case "FAILED":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
                break;
            //定位上报时间设置发送button监听
            case R.id.location_updata_time_btn:
                if (locationUpdataTime_editText.getText().toString().trim().length() == 0) {
                    Toast.makeText(getActivity(), R.string.instant_loaction_cant_null, Toast.LENGTH_SHORT).show();
                    return;
                }
                int time = Integer.parseInt(locationUpdataTime_editText.getText().toString());
                //判断输入内容范围
                if (time < 10 || time > 600) {
                    Toast.makeText(getActivity(), R.string.toast_instant_loaction, Toast.LENGTH_SHORT).show();
                    locationUpdataTime_editText.setText("");
                    return;
                }
                carPresenter.setLocationTime(UrlAddress.SET_LOCATION_TIME, String.valueOf(terminalId), String.valueOf(time), new BasePresenter.OnUIThreadListener<Result>() {
                    @Override
                    public void onBefore(Request request, int id) {

                    }

                    @Override
                    public void onAfter(int id) {

                    }

                    @Override
                    public void onError(Call call, Exception e, int i) {
                        Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Result result) {
                        switch (result.getStatus()) {
                            case "OK":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                            case "FAILED":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
                break;
            //设备重启指令发送button监听
            case R.id.reset_terminal_btn:
                carPresenter.resetTerminal(UrlAddress.RESET_TERMINAL, String.valueOf(terminalId), new BasePresenter.OnUIThreadListener<Result>() {
                    @Override
                    public void onBefore(Request request, int id) {

                    }

                    @Override
                    public void onAfter(int id) {

                    }

                    @Override
                    public void onError(Call call, Exception e, int i) {
                        Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Result result) {
                        switch (result.getStatus()) {
                            case "OK":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                            case "FAILED":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
                break;
            case R.id.overspeed_alarm_set_btn:
                if (overspeedAlarmSpeed_editText.getText().toString().trim().length() == 0) {
                    Toast.makeText(getActivity(), R.string.overspeed_alarm_speed_cant_null, Toast.LENGTH_SHORT).show();
                    return;
                }
                //获得输入的速度值
                float speed = Integer.parseInt(overspeedAlarmSpeed_editText.getText().toString());
                carPresenter.setSpeedWarning(UrlAddress.SET_SPEED_WARNING, String.valueOf(terminalId), String.valueOf(speed), new BasePresenter.OnUIThreadListener<Result>() {
                    @Override
                    public void onBefore(Request request, int id) {

                    }

                    @Override
                    public void onAfter(int id) {

                    }

                    @Override
                    public void onError(Call call, Exception e, int i) {
                        Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Result result) {
                        switch (result.getStatus()) {
                            case "OK":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                            case "FAILED":
                                Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
                break;
        }
    }

    //设置spinner item点击监听
    private void setSpinnerItemClick() {
        alarmSendType_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] reportTheWay = getResources().getStringArray(R.array.report_the_way);
                alarmSendTypeSelected = reportTheWay[position].equals("平台") ? "TERRACE" : "TERRACEANDSMS";
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}
